<template>
	<view class="main">
		<!-- <view class="top">			
			<image src="../../static/images/top2.png" class="topImg"></image>
			<view class="title">诉求直通</view>
		</view> -->
		<my-header :title="title" :index="true"></my-header>
		<view style="margin-top: 60px;">
			<uni-segmented-control :current="current" :values="items" style-type="button"
				active-color="#007aff" @clickItem="onClickItem" />
		</view>
		<view class="content">
			<view v-if="current === 0">
				<uni-forms ref="customForm" :rules="customRules" :modelValue="customFormData">
					<uni-section title="诉求信息" type="line" titleFontSize="16px"/>		
					<uni-card class='formCard'>						
						<!-- <uni-forms-item label="企业名称" required name="enterpriseName" :label-width="80">
							<uni-easyinput v-model="customFormData.enterpriseName" placeholder="请输入企业名称" />
						</uni-forms-item> -->
						<uni-forms-item label="诉求类型" required name="demandType" :label-width="80">
							<uni-data-select v-model="customFormData.demandType" :localdata="range"></uni-data-select>
						</uni-forms-item>
					<!-- 	<uni-forms-item label="诉求标题" required name="demandTitle" :label-width="80">
							<uni-easyinput v-model="customFormData.demandTitle" placeholder="请输入诉求标题" />
						</uni-forms-item> -->
						<uni-forms-item label="诉求内容" required name="demandContent" :label-width="80">
							<uni-easyinput type="textarea" v-model="customFormData.demandContent" placeholder="请输入诉求内容" />
						</uni-forms-item>
						<uni-forms-item label="诉求图片" name="imageValue" :label-width="80">
							<!-- <uni-file-picker limit="9" title="最多选择9张图片" @success="success" @select="select"></uni-file-picker> -->
							<uni-file-picker 
								v-model="imageValue" 
								fileMediatype="image" 
								mode="grid" 
								@select="select" 
								@delete="deleteImg" 
								@success="success" 
								@fail="fail"
							/>
							
						</uni-forms-item>	
						<uni-forms-item label="诉求时间" name="createTime" :label-width="80">
							<uni-datetime-picker type="date" :clear-icon="false" v-model="customFormData.createTime" />
						</uni-forms-item>
					</uni-card>
					<uni-section title="提交人信息" type="line" titleFontSize="16px"/>		
					<uni-card class='formCard'>
						<uni-forms-item label="提交人" required name="submitter" :label-width="80">
							<uni-easyinput v-model="customFormData.submitter" placeholder="请输入姓名" />
						</uni-forms-item>
						<uni-forms-item label="联系方式" required name="contact" :label-width="80">
							<uni-easyinput v-model="customFormData.contact" placeholder="请输入联系方式" />
						</uni-forms-item>
					</uni-card>			
					<button type="primary" @click="submit('customForm')">提交诉求</button>	
				</uni-forms>
			</view>
			<view v-if="current === 1">
				<uni-forms ref="recruitForm" :rules="recruitRules" :modelValue="recruitFormData">
					<uni-card class='formCard'>						
						<!-- <uni-forms-item label="企业名称" required name="enterpriseName" :label-width="80">
							<uni-easyinput v-model="recruitFormData.enterpriseName" placeholder="请输入企业名称" />
						</uni-forms-item> -->
						<uni-forms-item label="岗位名称" required name="recruitPosition" :label-width="80">
							<uni-easyinput v-model="recruitFormData.recruitPosition" placeholder="请输入岗位名称" />
						</uni-forms-item>
						<uni-forms-item label="岗位描述" required name="responsibilities" :label-width="80">
							<uni-easyinput type="textarea" v-model="recruitFormData.responsibilities" placeholder="请输入岗位描述" />
							<!-- <editor id="editor" placeholder="开始输入..." show-img-size show-img-toolbar
								show-img-resize >
							</editor>
							<button @tap="testEditor">333</button> -->
						</uni-forms-item>
						<uni-forms-item label="学历要求" required name="education" :label-width="80">
							<uni-data-select v-model="recruitFormData.education" :localdata="educationList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item label="招聘人数" required name="headcount" :label-width="80">
							<uni-easyinput type="number" v-model="recruitFormData.headcount" placeholder="请输入整数"></uni-easyinput>
						</uni-forms-item>
						<uni-forms-item label="招聘要求" required name="recruitRequires" :label-width="80">
							<uni-easyinput type="textarea" v-model="recruitFormData.recruitRequires" placeholder="请输入招聘要求" />
						</uni-forms-item>
						<uni-forms-item label="薪资类型" required name="salaryType" :label-width="80">
							<uni-data-select v-model="recruitFormData.salaryType" :localdata="salaryTypeList"></uni-data-select>
						</uni-forms-item>
						<uni-forms-item v-if="recruitFormData.salaryType !== '面议' && recruitFormData.salaryType !== ''" label="薪资待遇" required name="salary" :label-width="80">
							<uni-easyinput v-model="recruitFormData.salary" placeholder="请输入薪资待遇" />
						</uni-forms-item>
						<uni-forms-item label="联系人联系方式" required name="contact" :label-width="80">
							<uni-easyinput v-model="recruitFormData.contact" placeholder="请输入联系人联系方式" />
						</uni-forms-item>
						<uni-forms-item label="提供住宿" required name="accommodation" :label-width="100">
							<uni-data-checkbox v-model="recruitFormData.accommodation" :localdata="radioList"></uni-data-checkbox>
						</uni-forms-item>
						<uni-forms-item label="提供工作餐" required name="workMeal" :label-width="100">
							<uni-data-checkbox v-model="recruitFormData.workMeal" :localdata="radioList"></uni-data-checkbox>
						</uni-forms-item>
						<uni-forms-item label="截止时间" required name="deadline" :label-width="80">
							<uni-datetime-picker type="date" :clear-icon="false" v-model="recruitFormData.deadline" />
						</uni-forms-item>
						</uni-card>	
					<button type="primary" @click="submit('recruitForm')">提交招聘</button>	
				</uni-forms>
			</view>
		</view>
		<uni-popup ref="inputDialog" type="dialog">
			<view class="inputDialog">
				<uni-forms ref="hisForm" :rules="hisFormRules" :modelValue="hisFormData" class='inputFull'>
					<uni-forms-item name="contact">
						<uni-easyinput v-model="hisFormData.contact" placeholder="请输入手机号"></uni-easyinput>
					</uni-forms-item>
					<uni-forms-item name="verificationCode">
						<uni-easyinput v-model="hisFormData.verificationCode" placeholder="请输入验证码">
							<template #right>
									<button size="mini" type="primary" :disabled="ddl != 60" @click="getCode">{{ddl == 60 ? '点击获取' : ddl + 's'}}</button>	
								</template>
						</uni-easyinput>
					</uni-forms-item>									
				</uni-forms>
				<view class="dialogBtns">
					<view class="closeBtn" @click="close">取消</view>	
					<view class="confirmBtn" @click="toHis">确定</view>	
				</view>
			</view>
			<!-- </uni-popup-dialog> -->
		</uni-popup>
		
	</view>
</template>

<script>
	import MyHeader from '@/components/header.vue'
	export default {
		components: {
			MyHeader,
		},
		data() {
			return {
				title: '益企提',
				// 自定义表单校验规则
				customRules: {
					// enterpriseName: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入企业名称'
					// 	}]
					// },
					demandType: {
						rules: [{
							required: true,
							errorMessage: '请选择诉求类型'
						}]
					},
					// demandTitle: {
					// 	rules: [{
					// 		required: true,
					// 		errorMessage: '请输入诉求标题'
					// 	}]
					// },
					demandContent: {
						rules: [{
							required: true,
							errorMessage: '请输入诉求内容'
						}]
					},
					submitter: {
						rules: [{
							required: true,
							errorMessage: '请输入姓名'
						}]
					},
					contact: {
						rules: [{
							required: true,
							errorMessage: '请输入联系方式'
						}]
					},
				},
				hisFormRules: {
					contact: {
						rules: [{
							required: true,
							errorMessage: '请输入手机号'
						}]
					},
					verificationCode: {
						rules: [{
							required: true,
							errorMessage: '请输入验证码'
						}]
					},
				},
				// 自定义表单数据
				customFormData: {
					// enterpriseName: '',
					demandType: 0,
					// demandTitle: '',
					demandContent: '',
					submitter: '',
					contact: '',					
					files:[],
					createTime: null,
				},
				hisFormData: {
					contact: '',
					verificationCode: ''
				},
				// contact: '',
				// verificationCode: '',
				ddl: 60,
				range: [
				  { value: 1, text: "要素保障" },
				  { value: 2, text: "人力社保" },
				  { value: 3, text: "安全生产" },
				  { value: 4, text: "市场监督" },
				  { value: 5, text: "政策咨询" },
				  { value: 6, text: "融资贷款" },
				  { value: 7, text: "市场销售" },
				  { value: 8, text: "法律咨询" },
				  { value: 9, text: "企业发展" },
				  { value: 10, text: "其他" },
				],
				educationList: [
					{ text: '不限', value: '不限'},
				    { text: '小学', value: '小学'},
				    { text: '初中', value: '初中'},
				    { text: '初中及以上', value: '初中及以上'},
				    { text: '中专', value: '中专'},
				    { text: '中专及以上', value: '中专及以上'},
				    { text: '高中', value: '高中'},
				    { text: '高中及以上', value: '高中及以上'},
				    { text: '中专/高中', value: '中专/高中'},
				    { text: '中专/高中及以上', value: '中专/高中及以上'},
				    { text: '大专', value: '大专'},
				    { text: '大专及以上', value: '大专及以上'},
				    { text: '本科', value: '本科'},
				    { text: '本科及以上', value: '本科及以上'},
				    { text: '硕士及以上', value: '硕士及以上'}
				],
				salaryTypeList: [
					{ text: '面议', value: '面议'},
				    { text: '月薪', value: '月薪'},
				    { text: '年薪', value: '年薪'},
				],
				radioList: [{
					text: '是',
					value: 1
				}, {
					text: '否',
					value: 0
				}],
				ifHis: true,
				imageValue: [],
				items: ['诉求直通', '企业招聘'],
				current: 0,
				recruitFormData: {
					recruitPosition: '',
					responsibilities: '',
					education: '',
					headcount: '',
					recruitRequires: '',
					salaryType: '',
					salary: '',
					contact: '',
					accommodation: 1,
					workMeal: 1
				},
				recruitRules: {
					recruitPosition: {
						rules: [{
							required: true,
							errorMessage: '请输入岗位名称'
						}]
					},
					responsibilities: {
						rules: [{
							required: true,
							errorMessage: '请输入岗位描述'
						}]
					},
					education: {
						rules: [{
							required: true,
							errorMessage: '请选择学历要求'
						}]
					},
					headcount: {
						rules: [{
							required: true,
							errorMessage: '请输入招聘人数'
						}]
					},
					recruitRequires: {
						rules: [{
							required: true,
							errorMessage: '请输入招聘要求'
						}]
					},
					salaryType: {
						rules: [{
							required: true,
							errorMessage: '请选择薪资类型'
						}]
					},
					salary: {
						rules: [{
							required: true,
							errorMessage: '请输入薪资待遇'
						}]
					},
					contact: {
						rules: [{
							required: true,
							errorMessage: '请输入联系人联系方式'
						}]
					},	
					deadline: {
						rules: [{
							required: true,
							errorMessage: '请选择截止时间'
						}]
					}
				},
				shuangfengData: {},
				editorCtx: ''
			}
		},
		onLoad() {
			
		}, 
		onShow() {
			//获取本地保存账号信息 修改登录状态
			let that = this
			uni.getStorage({
				key: 'shuangfengData',
				success: function (res) {
					that.shuangfengData = res.data
					console.log(res.data, that.shuangfengData);
				}
			});
			let nowDate = new Date()
			this.customFormData.createTime = nowDate.getFullYear() + '-' + (nowDate.getMonth() + 1).toString().padStart(2, '0') + '-' + nowDate.getDate().toString().padStart(2, '0')
		},
		methods: {
			onClickItem(e) {
				if (this.current !== e.currentIndex) {
					this.current = e.currentIndex
				}
			},
			// 获取上传状态
			select(e){
				console.log(e, 'eeeee')	
				uni.showLoading({
					title: '上传中'
				});
				
				for(let i = 0; i < e.tempFilePaths.length; i++) {		
					const file = e.tempFilePaths[i]; // 获取选中的文件		
					uni.uploadFile({
						url:'/sf_enterprise_service/business/file/upload',
						filePath: file,
						success: (uploadRes) => {
						  let res = JSON.parse(uploadRes.data)
						  this.customFormData.files.push(res.fileId)
						  console.log('upload success:', res.fileId, this.customFormData);
						  // 处理上传成功后的逻辑
						  uni.hideLoading();
						},
						fail: (uploadErr) => {
						  console.error('upload fail:', uploadErr);
						  // 处理上传失败的逻辑
						}
					 });
					 if(i == e.tempFilePaths.length - 1)
						uni.hideLoading();
				 }
			},
			deleteImg(e) {
				console.log(e)
				this.customFormData.files.splice(e.index, 1)
				console.log(this.customFormData.files)
			},
			testUpload() {
				this.$refs.files.upload()
			},
			// 获取上传进度
			progress(e){
				console.log('上传进度：',e)
			},
			
			// 上传成功
			success(e){
				console.log('上传成功e', e, this.customFormData.files)
				
			},
			
			// 上传失败
			fail(e){
				console.log('上传失败：',e)
			},
			inputDialogToggle() {
				this.$refs.inputDialog.open()
			},
			// 获取验证码
			getCode() {
				if(this.hisFormData.contact.length == 11) {
					uni.showLoading({
						title: '加载中'
					});
					// 走接口
					// 倒计时不可点击
					uni.request({
						url: '/sf_enterprise_service/business/sms/send/' + this.hisFormData.contact,
						// data: this.customFormData,
						method: 'GET',
						success: (res) => {		
							console.log(res, 'res??')
							uni.hideLoading();
							if(res.data.code == 0) {
								uni.showToast({
									title: '已发送，五分钟内有效',
									duration: 2000
								});
								let that = this
								let Interval = setInterval(() => {
									changeCodeDel()
								}, 1000)
								function changeCodeDel() {
									if(that.ddl > 0) {        
									  that.ddl --
									} else {
									  that.ddl = 60;
									  clearInterval(Interval)
									}
								  }
							} else {
								uni.showToast({
									title: res.data.msg,
									duration: 2000
								});
							}
						},
						complete: () => {							
							uni.hideLoading();
						}
					})
	
				} else {
					uni.showToast({
						title: '请填写正确手机号',
						icon: 'none'
					})
				}
			},
			// 查看历史申诉
			dialogInputConfirm(val) {
				// console.log(this.customForm, 'customForm')
				// return
				uni.request({
					url: '/sf_enterprise_service/business/demand/queryPage', 
					data: this.customForm,
					method: 'GET',
					success: (res) => {
						// console.log(res.data, res.data.data, res.data.totalCount, 'res');				
						if(res.data.data.totalCount) {	
							let jsonList = JSON.stringify(res.data.data.list)
							this.toHis(res.data.data.list)
						} else {
							uni.showToast({
								title: '暂无历史诉求',
								icon: 'none',
								duration: 2000
							})
						}
					},
					complete: () => {							
						uni.hideLoading();
					}
				})
			},
			close() {
				this.$refs.inputDialog.close()
			},
			// 展示历史申诉
			toHis() {					
				console.log('tohis')
				this.$refs['hisForm'].validate().then(res => {
					console.log('success', res);
					uni.request({
						url: '/sf_enterprise_service/business/anondemand/selflist/',
						data: {
							contact: this.hisFormData.contact,
							code: this.hisFormData.verificationCode
						},
						method: 'GET',
						success: (res) => {		
							console.log(res, 'res??')
							if(res.data.data?.length) {	
								uni.navigateTo({
									url: '/pages/form/hisForm?detail=' + JSON.stringify(res.data.data),
								})
							} else {
								uni.showToast({
									title: res.data.msg,
									icon: 'none',
									duration: 2000
								})
							}
						},
						complete: () => {							
							uni.hideLoading();
						}
					})
					
				}).catch(err => {
					console.log('err', err);
				})
				
			},
			submit(ref) {
				console.log('submit', this[ref+'Data']);
				// return
				if(ref == 'customForm') {
					this.$refs[ref].validate().then(res => {
						if(typeof(this.customFormData.files) == 'object') {
							this.customFormData.files = this.customFormData.files.join()
						}
						console.log('success', this.customFormData);
						// return
						uni.showLoading({
							title: '加载中'
						});
						// 上传图片 ？
						// 表单提交
						uni.request({
							// url: '/api/users',
						    url: '/sf_enterprise_service/business/demand/save', 
						    data: this.customFormData,
							method: 'POST',
							header: {
								'Token': this.shuangfengData.token
							},
						    success: (res) => {
						        console.log(res.data, 'res');
								if(res.data.code == 0) {
									this.customFormData = {
										// enterpriseName: '',
										demandType: 0,
										demandTitle: '',
										demandContent: '',
										submitter: '',
										contact: '',
										files: [],
									}
									this.imageValue = []
									uni.showToast({
										title: '提交成功',
										duration: 2000
									})
								} else {
									uni.showToast({
										title: res.data.msg,
										duration: 2000,
										icon: 'none'
									})
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}, 1000)
								}
						    },
							complete: () => {							
								uni.hideLoading();
							}
						});
					}).catch(err => {
						console.log('err', err);
					})
				} else {
					this.$refs[ref].validate().then(res => {
						this.recruitFormData.accommodation = Boolean(this.recruitFormData.accommodation)
						this.recruitFormData.workMeal = Boolean(this.recruitFormData.workMeal)
						if(this.recruitFormData.salaryType == '面议' || this.recruitFormData.salaryType == '') {
							this.recruitFormData.salary = ''
						}
						// return
						uni.showLoading({
							title: '加载中'
						});
						// 表单提交
						uni.request({
						    url: '/sf_enterprise_service/business/recruit/add', //仅为示例，并非真实接口地址。
						    data: this.recruitFormData,
							method: 'POST',
							header: {
								'Token': this.shuangfengData.token
							},
						    success: (res) => {
						        console.log(res.data, 'res');
								if(res.data.code == 0) {
									this.recruitFormData = {
										recruitPosition: '',
										responsibilities: '',
										education: '',
										headcount: '',
										recruitRequires: '',
										salaryType: '',
										salary: '',
										contact: '',
										accommodation: 1,
										workMeal: 1
									}
									uni.showToast({
										title: '提交成功',
										duration: 2000
									})
								} else {
									uni.showToast({
										title: res.data.msg,
										duration: 2000,
										icon: 'none'
									})
									setTimeout(() => {
										uni.navigateTo({
											url: '/pages/login/login'
										})
									}, 1000)
								}
								
						    },
							complete: () => {							
								uni.hideLoading();
							}
						});
					}).catch(err => {
						console.log('err', err);
					})
				}								
			},
			choseFile() {
				uni.chooseImage({
					success: (chooseImageRes) => {
						const tempFilePaths = chooseImageRes.tempFilePaths;
						uni.uploadFile({
							url: 'https://www.example.com/upload', //仅为示例，非真实的接口地址
							filePath: tempFilePaths[0],
							name: 'file',
							formData: {
								'user': 'test'
							},
							success: (uploadFileRes) => {
								console.log(uploadFileRes.data);
							}
						});
					}
				});
			},
			testEditor() {					
				this.editorCtx.getContents(res => {
					console.log(res, 'reeee')
				})
			},
			testFiles(e) {
				console.log(e, 'e')
				return
				const tempFilePaths = e.tempFilePaths;
				//获取图片临时路径
				const imgUrl=tempFilePaths[0]
				uni.uploadFile({
				  //图片上传地址
				  url: 'https://xxx.xxx.com/api/uploadpic/', 
				  filePath: imgUrl,
				  //上传名字，注意与后台接收的参数名一致
				  name: 'imgUrl',
				  //设置请求头
				  header:{"Content-Type": "multipart/form-data"},
				  //请求成功，后台返回自己服务器上的图片地址
				  success: (uploadFileRes) => {
					console.log('uploadFileRes',JSON.parse(uploadFileRes.data));   
					//处理数据
					const path=JSON.parse(uploadFileRes.data)
					//赋值，前端渲染
					this.baseFormData.photo=path.imgUrl
				  }
				});
			}
		}
	}
</script>

<style>
	.main {
		position: relative;
	}
	.uni-page-head {
		display: none !important;
	}
	.inputFull {
		width: 100%;
	}
	.inputDialog {
		width: 80vw;
		background-color: #fff;
		border-radius: 10rpx;
		
	}
	.inputDialog .uni-forms {
		padding: 80rpx 40rpx 20rpx 40rpx;
		box-sizing: border-box;
	}
	.dialogBtns {
		display: flex;
		border-top: 1px solid #d3d3d3;	
		
	}
	.dialogBtns view {
		flex-grow: 1;
		text-align: center;
		padding: 20rpx 0;
	}
	.dialogBtns .confirmBtn {
		background-color: #5ab8ff;
		color: #fff;
	}
</style>
